#include "ObjLoader.h"

Mesh* ObjLoader::LoadObj(QString path)
{
	QFile _objfile(path);
	if (!_objfile.open(QIODevice::ReadOnly | QIODevice::Text))
	{
		return 0;
	}
	QTextStream _stream(&_objfile);

	QString line = _stream.readLine();
	Mesh *mesh = new Mesh();
	while (!line.isNull()) 
	{
		ProcessTextLine(line, mesh);
		line = _stream.readLine();
	}
	return mesh;
}

void ObjLoader::ProcessTextLine(QString &line, Mesh *mesh)
{
	if (line.isEmpty()) return;
	switch (line.at(0).toAscii())
	{
	case '#': 
		break;
	case 'v': 
		{
			QStringList coords= line.split(' ', QString::SkipEmptyParts, Qt::CaseInsensitive);
			Vertex3f *v = new Vertex3f(coords.at(1).toFloat(), coords.at(2).toFloat(), coords.at(3).toFloat());
			//init neighbors
			v->neighbors = new QList<Vertex3f*>();
			v->Color = new Color4b(0, 0, 0, 0);
			//
			mesh->vertices.append(v);
			break;
		}
	case 'f': 
		{
			QStringList faces= line.split(' ', QString::SkipEmptyParts, Qt::CaseInsensitive);
			Tri_Face *f = new Tri_Face();
			int one, two, three;
			one   = faces.at(1).split('/').at(0).toInt() -1;
			two   = faces.at(2).split('/').at(0).toInt() -1;
			three = faces.at(3).split('/').at(0).toInt() -1;


			//add neighbors
			f->p1 = mesh->vertices[one];
			if(!f->p1->neighbors->contains(mesh->vertices[two]))
				f->p1->neighbors->append(mesh->vertices[two]);
			if(!f->p1->neighbors->contains(mesh->vertices[three]))
				f->p1->neighbors->append(mesh->vertices[three]);

			f->p2 = mesh->vertices[two];
			if(!f->p2->neighbors->contains(mesh->vertices[one]))
				f->p2->neighbors->append(mesh->vertices[one]);
			if(!f->p2->neighbors->contains(mesh->vertices[three]))
				f->p2->neighbors->append(mesh->vertices[three]);

			f->p3 = mesh->vertices[three];
			if(!f->p3->neighbors->contains(mesh->vertices[one]))
				f->p3->neighbors->append(mesh->vertices[one]);
			if(!f->p3->neighbors->contains(mesh->vertices[two]))
				f->p3->neighbors->append(mesh->vertices[two]);

			mesh->faces.append(f);
			break;
		}
	}
}